#include<iostream>
using namespace std;
//https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/description/
//二叉树的最近公共祖先
//给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
//百度百科中最近公共祖先的定义为：“对于有根树 T 的两个节点 p、q，最近公共祖先表示为一个节点 x，满足 x 是 p、q 的祖先且 x 的深度尽可能大（一个节点也可以是它自己的祖先）。”

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
 
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root == nullptr)
            return nullptr;
        if(root == p || root == q)
            return root;

        TreeNode* leftFind = lowestCommonAncestor(root->left, p, q);
        TreeNode* rightFind = lowestCommonAncestor(root->right, p, q);

        if((leftFind == p && rightFind == q) || (leftFind == q && rightFind == p))
            return root;
        else if(leftFind == p || rightFind == p)
            return p;
        else if(leftFind == q || rightFind == q)
            return q;
        else if(leftFind == nullptr && rightFind == nullptr)
            return nullptr;
        else
            return leftFind != nullptr ? leftFind : rightFind;
    }
};

int main()
{
	TreeNode n1(1);
	TreeNode n2(2);
	TreeNode n3(3);
	n1.left = &n2;
	n1.right = &n3;
	cout << Solution().lowestCommonAncestor(&n1, &n3, &n2)->val << endl;

	return 0;
}